/*
 * Created by 2019年1月24日
 */
package top.v5it.japi.ddd.core.web;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.web.bind.annotation.*;
import top.v5it.japi.ddd.core.entity.ResultSet;
import top.v5it.japi.ddd.core.exception.NotFoundException;
import top.v5it.japi.ddd.core.service.QueryService;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static top.v5it.japi.ddd.core.web.BaseController.SERVICE_NAME_SUFFIX;

/**
 * The generate query controller
 *
 * @author fangang
 */
@RestController
public class QueryController {

    @RequestMapping(value = "query/{bean}", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultSet query(@PathVariable("bean") String beanName,
                           @RequestBody(required = false) Map<String, Object> params, HttpServletRequest request) {
        HttpHeadFactory.INSTANCE.putRequestHeadAll(ServletUtil.getHeaderMap(request));
        QueryService service = getBean(beanName);
        return service.query(params);
    }

    /**
     * get bean in the spring context by name.
     *
     * @param name the bean name
     * @return the instance of the bean
     */
    private QueryService getBean(String name) {
        final String serviceName =
                StrUtil.format("{}{}", StrUtil.toCamelCase(name, '-'), SERVICE_NAME_SUFFIX);
        try {
            return SpringUtil.getBean(serviceName, QueryService.class);
        } catch (NoSuchBeanDefinitionException e) {
            throw new NotFoundException();
        }
    }
}
